/*
 * Copyright (c) 2000-2019 TeamDev Ltd. All rights reserved.
 * TeamDev PROPRIETARY and CONFIDENTIAL.
 * Use is subject to license terms.
 */
package samples;

import static javax.swing.WindowConstants.EXIT_ON_CLOSE;

import com.teamdev.jxbrowser.chromium.BoundsListener;
import com.teamdev.jxbrowser.chromium.Browser;
import com.teamdev.jxbrowser.chromium.swing.BrowserView;
import java.awt.BorderLayout;
import java.awt.Rectangle;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;

/**
 * This example demonstrates how to listen to the update bounds JavaScript request sended via
 * window.resizeTo() and change frame size to the value specified in window.resizeTo() method.
 */
public final class BoundsListenerExample {

    static final String jsResizeCode = "resizeTo(400, 400)";

    public static void main(String[] args) {
        final Browser browser = new Browser();
        BrowserView view = new BrowserView(browser);

        final JFrame frame = new JFrame();
        JButton resize = new JButton(jsResizeCode);
        resize.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                browser.executeJavaScript(jsResizeCode);
            }
        });
        frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
        frame.add(view, BorderLayout.CENTER);
        frame.add(resize, BorderLayout.NORTH);
        frame.setSize(700, 500);
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);

        browser.addBoundsListener(new BoundsListener() {
            @Override
            public void onBoundsUpdateRequested(Rectangle bounds) {
                frame.setSize(bounds.getSize());
            }
        });

        browser.loadURL("https://www.google.com");
    }
}
